package edu.gyu.myshop.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import edu.gyu.myshop.model.Goods;
import edu.gyu.myshop.model.Goodstype;
import edu.gyu.myshop.model.OrderDetail;
import edu.gyu.myshop.service.GoodsService;
import edu.gyu.myshop.service.GoodstypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
public class GoodsController {
    @Autowired
    GoodsService goodsService;
    @Autowired
    GoodstypeService goodstypeService;
    private static final String UPLOAD_FOLDER = System.getProperty("user.dir") + "/src/main/resources/static/image/";

    @RequestMapping("/type")
    public String myGoods(String tid, Model model) {
        List<Goods> goodsList = goodsService.lambdaQuery()
                .eq(Goods::getGoodstypeId, tid)
                .list();
        model.addAttribute("goodsList", goodsList);
        return "/list";
    }

    @RequestMapping("/search")
    public String search(String name, Model model) {

        List<Goods> goodsList = goodsService.lambdaQuery()
                .like(Goods::getName, name)
                .list();

        model.addAttribute("goodsList", goodsList);
        return "/list";
    }


    @RequestMapping("/goodsDetail")
    public String goods(String id, String msg, Model model) {


        Goods goods = goodsService.lambdaQuery()
                .eq(Goods::getId, id)
                .one();

        Goodstype goodstype = goodstypeService.lambdaQuery()
                .eq(Goodstype::getId, goods.getGoodstypeId())
                .one();
        goods.setTypename(goodstype.getTypename());

        model.addAttribute("goods", goods);
        if (msg != null) {
            model.addAttribute("msg4", msg);
        }
        return "/goods";
    }

    @RequestMapping("/admin/goodsadd")
    public String goodsAdd(Model model) {
        List<Goodstype> goodstypeList = goodstypeService.list();
        model.addAttribute("goodstypeList", goodstypeList);
        return "/pages/goodsadd";
    }

    @RequestMapping("/admin/goodsaddPost")
    public String goodsAddPost(@RequestParam("name") String name,
                               @RequestParam("price") double price,
                               @RequestParam("store") int store,
                               @RequestParam("picture") MultipartFile picture,
                               @RequestParam("goodstype_id") int goodstypeId,
                               @RequestParam("isRecommend") int isRecommend,
                               @RequestParam("is_new") int isNew,
                               RedirectAttributes redirectAttributes) {
        try {
            // 确保上传目录存在
            File uploadDir = new File(UPLOAD_FOLDER);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }

            // 检查图片是否已经存在
            String originalFilename = picture.getOriginalFilename();
            Path filePath = Paths.get(UPLOAD_FOLDER + originalFilename);
            if (Files.exists(filePath)) {
                // 如果文件存在，生成新的文件名
                String newFilename = generateNewFilename(originalFilename);
                filePath = Paths.get(UPLOAD_FOLDER + newFilename);
                originalFilename = newFilename;
            }

            // 保存图片到服务器
            byte[] bytes = picture.getBytes();
            Files.write(filePath, bytes);

            // 保存商品信息到数据库
            Goods product = new Goods();
            product.setName(name);
            product.setPrice(price);
            product.setStore(store);
            product.setPicture(originalFilename);
            product.setGoodstypeId(goodstypeId);
            product.setIsrecommend(isRecommend);
            product.setIsNew(isNew);
            goodsService.save(product);

            redirectAttributes.addFlashAttribute("msg4", "商品发布成功");
        } catch (IOException e) {
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("msg4", "商品发布失败，请重试");
        }
        return "redirect:/admin/goodsList";
    }


    @RequestMapping("/admin/goodsList")
    public String goodsList(@RequestParam(value = "page", defaultValue = "1") int page,
                            @RequestParam(value = "size", defaultValue = "10") int size,
                            Model model) {
        Page<Goods> pageRequest = new Page<>(page, size);
        // 使用 QueryWrapper 指定排序条件
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id"); // 按 id 倒序排序
        // 使用分页方式获取商品列表
        Page<Goods> productPage = goodsService.page(pageRequest, queryWrapper);
        // 设置商品类别名称
        productPage.getRecords().forEach(good -> {
            Goodstype goodstype = goodstypeService.lambdaQuery().eq(Goodstype::getId, good.getGoodstypeId()).one();
            if (goodstype != null) {
                good.setTypename(goodstype.getTypename());
            }
        });
        long totalPages = productPage.getPages();
        long currentPage = productPage.getCurrent();
        long totalRecords = productPage.getTotal();
        model.addAttribute("totalPages", totalPages);
        model.addAttribute("currentPage", currentPage);
        model.addAttribute("totalRecords", totalRecords);
        model.addAttribute("productPage", productPage);
        return "/pages/goodsList";
    }

    @RequestMapping("/admin/productdelete/{id}")
    public String goodsDelete(@PathVariable("id") int id, RedirectAttributes redirectAttributes) {
        goodsService.removeById(id);
        redirectAttributes.addFlashAttribute("msg4", "商品删除成功");
        return "redirect:/admin/goodsList";
    }

    @RequestMapping("/admin/productdetail/{id}")
    public String goodsUpdate(@PathVariable("id") int id, Model model) {
        Goods goods = goodsService.lambdaQuery().eq(Goods::getId, id).one();
        List<Goodstype> goodstypeList = goodstypeService.list();
        goods.setTypename(goodstypeService.lambdaQuery().eq(Goodstype::getId, goods.getGoodstypeId()).one().getTypename());
        model.addAttribute("goods", goods);
        model.addAttribute("goodstypeList", goodstypeList);
        return "/pages/goodsupdate";
    }

    @RequestMapping("/admin/goodsupdatePost")
    public String goodsUpdatePost(@RequestParam("id") int id,
                                  @RequestParam("name") String name,
                                  @RequestParam("price") double price,
                                  @RequestParam("store") int store,
                                  @RequestParam("picture") MultipartFile picture,
                                  @RequestParam("goodstype_id") int goodstypeId,
                                  @RequestParam("isRecommend") int isRecommend,
                                  @RequestParam("is_new") int isNew,
                                  RedirectAttributes redirectAttributes) {
        try {
            Goods product = goodsService.lambdaQuery().eq(Goods::getId, id).one();
            if (product == null) {
                redirectAttributes.addFlashAttribute("msg4", "未找到商品");
                return "redirect:/admin/product/list";
            }

            // 更新商品信息
            product.setName(name);
            product.setPrice(price);
            product.setStore(store);
            product.setGoodstypeId(goodstypeId);
            product.setIsrecommend(isRecommend);
            product.setIsNew(isNew);

            if (!picture.isEmpty()) {
                // 确保上传目录存在
                File uploadDir = new File(UPLOAD_FOLDER);
                if (!uploadDir.exists()) {
                    uploadDir.mkdirs();
                }

                // 检查图片是否已经存在
                String originalFilename = picture.getOriginalFilename();
                Path filePath = Paths.get(UPLOAD_FOLDER + originalFilename);
                if (Files.exists(filePath)) {
                    // 如果文件存在，生成新的文件名
                    String newFilename = generateNewFilename(originalFilename);
                    filePath = Paths.get(UPLOAD_FOLDER + newFilename);
                    originalFilename = newFilename;
                }

                // 保存图片到服务器
                byte[] bytes = picture.getBytes();
                Files.write(filePath, bytes);

                // 更新商品图片文件名
                product.setPicture(originalFilename);
            }

            goodsService.updateById(product);
            redirectAttributes.addFlashAttribute("msg4", "商品更新成功");
        } catch (IOException e) {
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("msg4", "商品更新失败，请重试");
        }
        return "redirect:/admin/goodsList";
    }

    private String generateNewFilename(String originalFilename) {
        String timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String extension = "";
        int dotIndex = originalFilename.lastIndexOf('.');
        if (dotIndex >= 0) {
            extension = originalFilename.substring(dotIndex);
            originalFilename = originalFilename.substring(0, dotIndex);
        }
        return originalFilename + "_" + timestamp + extension;
    }
}